﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace David.Framework.Core.Helper
{
    public class CommonTool
    {
        public static string GetMacAddress()
        {
            try
            {
                string mac = "";
                ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration");
                ManagementObjectCollection moc = mc.GetInstances();
                foreach (ManagementObject mo in moc)
                {
                    if ((bool)mo["IPEnabled"] == true)
                    {
                        mac = mo["MacAddress"].ToString();
                        break;
                    }
                }
                moc = null;
                mc = null;
                return mac;
            }
            catch
            {
                return "unknow";
            }
        }
        public static string getIP()
        {
            var userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (string.IsNullOrEmpty(userHostAddress))
            {
                userHostAddress = HttpContext.Current.Request.UserHostAddress;
            }
            if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
            {
                return userHostAddress;
            }
            return "127.0.0.1";
        }
        public static bool IsIP(string ip)
        {
            return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
        }
        /// <summary>
        /// 截取字符串
        /// </summary>
        /// <param name="zf">字符</param>
        /// <param name="cd">长度</param>
        /// <returns></returns>
        public static string cutStr(string zf, int cd)
        {
            if (zf.Length > cd)
            {
                zf = zf.Substring(0, cd) + "...";
            }
            return zf;
        }

        /// <summary>
        /// 清除HTML代码截取字符串
        /// </summary>
        /// <param name="zf"></param>
        /// <param name="cd"></param>
        /// <returns></returns>
        public static string cutHtml(string zf, int cd)
        {
            if (!string.IsNullOrEmpty(zf))
            {

                Regex reg = new Regex("<.*?>");
                string wz = reg.Replace(zf, "");
                return cutStr(wz, cd);
            }
            return "";
        }
    }
}
